package com.hcr.kingdeeutil.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hcr.kingdeeutil.result.kingdeeResult;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author sky
 */
public class InvokeHelper {
    //    private static String accessToken = null;
    private static Map<String, Object> map = new HashMap<>(16);
    // 连接池 支持多个环境
    private static Map<String, Map<String,String>> cookieMap = new HashMap<>(16);
    //    private static String POST_K3CloudURL = null;
    private static Gson gson;

    static {
        map.put("Save", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");
        map.put("View", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc");
        map.put("Submit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        map.put("Delete", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc");
        map.put("Audit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        map.put("UnAudit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");
        map.put("StatusConvert", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc");
        map.put("ExecuteBillQuery", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");
        gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
                .create();
    }

    /**
     * HttpURLConnection
     */
    private static HttpURLConnection initUrlConn(String url, JsonArray paras, String POST_K3CloudURL,String accessToken)throws Exception {
        URL postUrl;
        HttpURLConnection connection;
        if (cookieMap.containsKey(accessToken)) {
            Map<String,String> cookieParamMap = cookieMap.get(accessToken);
            POST_K3CloudURL = cookieParamMap.get("k3Url");
            postUrl = new URL(POST_K3CloudURL.concat(url));
            connection = (HttpURLConnection) postUrl.openConnection();
            connection.setRequestProperty("Cookie",cookieParamMap.get("cookieKey"));
        }else{
            postUrl = new URL(POST_K3CloudURL.concat(url));
            connection = (HttpURLConnection) postUrl.openConnection();
        }
        if (!connection.getDoOutput()) {
            connection.setDoOutput(true);
        }
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json");
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());
        UUID uuid = UUID.randomUUID();
        int hashCode = uuid.toString().hashCode();
        JsonObject jObj = new JsonObject();
        jObj.addProperty("format", 1);
        jObj.addProperty("useragent", "ApiClient");
        jObj.addProperty("rid", hashCode);
        jObj.addProperty("parameters", chinaToUnicode(paras.toString()));
        jObj.addProperty("timestamp", new Date().toString());
        jObj.addProperty("v", "1.0");
        out.writeBytes(jObj.toString());
        out.flush();
        out.close();
        return connection;
    }

    public static String Login(String POST_K3Cloud_URL, String dbId, String user, String pwd, int lang)
            throws Exception {
        boolean bResult = false;
        String cookieValue = null;
        String accessToken = POST_K3Cloud_URL+dbId+user;
//        POST_K3CloudURL = POST_K3Cloud_URL;
        String sUrl = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";
        JsonArray jParas = new JsonArray();
        // 帐套Id
        jParas.add(dbId);
        // 用户名
        jParas.add(user);
        // 密码
        jParas.add(pwd);
        // 语言
        jParas.add(lang);
        HttpURLConnection connection = initUrlConn(sUrl, jParas, POST_K3Cloud_URL,"");
        // 获取Cookie
        String key = null;
        for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
            if ("Set-Cookie".equalsIgnoreCase(key)) {
                String tempaccessToken = connection.getHeaderField(i);
                if (tempaccessToken.startsWith("kdservice-sessionid")) {
                    cookieValue = tempaccessToken;
                    break;
                }
            }
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ");
        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
            String sResult = new String(line.getBytes(), "utf-8");
            System.out.println(sResult);
            bResult = line.contains("\"LoginResultType\":1");
        }
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ends ");
        System.out.println(" ============================= ");
        reader.close();
        connection.disconnect();
        if (bResult) {
            // 保存成功
            Map<String,String> cookieParamMap = new HashMap<>();
            cookieParamMap.put("k3Url",POST_K3Cloud_URL);
            cookieParamMap.put("cookieKey",cookieValue);
            cookieMap.put(accessToken, cookieParamMap);
        }
        return bResult?accessToken:null;
    }

    public static kingdeeResult Save(String formId, String content, String accessToken) throws Exception {
        return Invoke("Save", formId, content, accessToken);
    }

    public static kingdeeResult View(String formId, String content, String accessToken) throws Exception {
        return Invoke("View", formId, content, accessToken);
    }

    public static kingdeeResult Delete(String formId, String content, String accessToken) throws Exception {
        return Invoke("Delete", formId, content, accessToken);
    }

    public static kingdeeResult Submit(String formId, String content, String accessToken) throws Exception {
        return Invoke("Submit", formId, content, accessToken);
    }

    public static kingdeeResult Audit(String formId, String content, String accessToken) throws Exception {
        return Invoke("Audit", formId, content, accessToken);
    }

    public static kingdeeResult UnAudit(String formId, String content, String accessToken) throws Exception {
        return Invoke("UnAudit", formId, content, accessToken);
    }

    public static kingdeeResult StatusConvert(String formId, String content, String accessToken)
            throws Exception {
        return Invoke("StatusConvert", formId, content, accessToken);
    }

    public static String executeBillQuery(String content, String accessToken) throws Exception {
        String sResult = null;
        String sUrl = map.get("ExecuteBillQuery").toString();
        JsonArray jParas = new JsonArray();
        jParas.add(content);
        HttpURLConnection connectionInvoke = initUrlConn(sUrl, jParas,null, accessToken);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream()));
        String line;
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ");
        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes(), "utf-8");
            System.out.println(sResult);
        }
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ends ");
        System.out.println(" ============================= ");
        reader.close();
        connectionInvoke.disconnect();
        return sResult;
    }

    private static kingdeeResult Invoke(String deal, String formId, String content, String accessToken)
            throws Exception {
        String sResult = null;
        String sUrl = map.get(deal).toString();
        JsonArray jParas = new JsonArray();
        jParas.add(formId);
        jParas.add(content);
        HttpURLConnection connectionInvoke = initUrlConn(sUrl, jParas, null,accessToken);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream()));
        String line;
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ");
        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes(), "utf-8");
            System.out.println(sResult);
        }
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ends ");
        System.out.println(" ============================= ");
        reader.close();
        connectionInvoke.disconnect();
        JsonObject obj = gson.fromJson(sResult, JsonObject.class);
        kingdeeResult resultData = gson.fromJson(obj.getAsJsonObject("Result"), kingdeeResult.class);
        return resultData;
    }

    /**
     * 把中文转成Unicode码
     *
     * @param str
     * @return
     */
    public static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = (char) str.charAt(i);
            // 汉字范围 \u4e00-\u9fa5 (中文)
            if (chr1 >= 19968 && chr1 <= 171941) {
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }
}